package com.test.schoolhelper.ui.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import com.test.schoolhelper.R;
import com.test.schoolhelper.base.BaseActivity;
import com.test.schoolhelper.databinding.ActivityUserBinding;
import com.test.schoolhelper.db.DbUserController;
import com.test.schoolhelper.entity.User;
import com.test.schoolhelper.event.UserEvent;
import com.test.schoolhelper.ui.adapter.NewSAdapter;
import com.test.schoolhelper.ui.adapter.UserAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

// TODO: 2024/6/1 联系人
public class UserActivity extends BaseActivity<ActivityUserBinding> implements View.OnClickListener {

    private UserAdapter userAdapter;
    private List<User> list = new ArrayList<>();
    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        initAdapter();
    }

    private void initAdapter() {
        list= DbUserController.getInstance(this).searchAll();
        if (userAdapter==null){
            userAdapter = new UserAdapter(this, list);
            getBinding().rvData.setLayoutManager(new LinearLayoutManager(this,
                    LinearLayoutManager.VERTICAL, false));
            getBinding().rvData.setAdapter(userAdapter);
        }else {
            userAdapter.setList(list);
            userAdapter.notifyDataSetChanged();
        }

        userAdapter.setListener(pos -> {
            Intent intent = new Intent(this, UserDetailsActivity.class);
            intent.putExtra("data", list.get(pos));
            startActivity(intent);
        });
    }

    @Override
    protected void initClick() {
        super.initClick();
        getBinding().ivBack.setOnClickListener(this);
        getBinding().ivAdd.setOnClickListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(UserEvent event) {
        initAdapter();
    }
    @Override
    protected int initLayout() {
        return R.layout.activity_user;
    }

    @Override
    protected ActivityUserBinding onCreateViewBinding(@NonNull LayoutInflater layoutInflater) {
        return ActivityUserBinding.inflate(layoutInflater);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_add:
              startActivity(new Intent(this, AddUserActivity.class));
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}